
import React from 'react'
import { Form, Input, Button, Checkbox, message } from 'antd';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { fetchUserFromStorage, setUserStorage } from '../utils/storage';
import { useDispatch } from 'react-redux';
import {useNavigate} from "react-router";
import { setUser } from '../store/action';
import { useCheckAndNavigate } from '../utils';
import './Login.scss'
import { httpLoginUser } from '../apis';

export default function Login() {
  useCheckAndNavigate();
  const dispatcher = useDispatch();
  const navigate = useNavigate();
  const onFinish = async (values) => {
    console.log('Success:', values);
    let res = await httpLoginUser(values);
    if(res === "用户名或者密码错误") {
      message.error("用户名或者密码错误");
    } else {
      setUserStorage(res,values.remember);
      console.log(res);
      dispatcher(setUser(res));
      message.success("登录成功~");
      navigate("/home");
    }
  };

  return (
    <div className='loginContainer'>
      <Form
        name="login"
        labelCol={{ span: 7 }}
        wrapperCol={{ span: 12 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="用户名"
          name="name"
          rules={[{ required: true, message: 'Please input your username!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: 'Please input your password!' }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 6, span: 16 }}>
          <Checkbox>Remember me</Checkbox>
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 7}}>
          <Button type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 7 }}>
            <Link to={"/registe"}><button class='myBtn' type='button'>注 册</button></Link>
        </Form.Item>
      </Form>
    </div>
  )
}
